package cn.demo.framework.config;

import cn.demo.common.mybatisFlex.MyPermissionDialect;
import cn.demo.common.utils.CollectionUtils;
import cn.demo.common.utils.StringUtils;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.dialect.DialectFactory;
import com.mybatisflex.core.keygen.KeyGenerators;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.core.query.QueryColumnBehavior;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Configuration
public class MyBatisFlexConfiguration implements MyBatisFlexCustomizer, ConfigurationCustomizer {

    private static final Logger logger = LoggerFactory.getLogger("sql");


    public MyBatisFlexConfiguration() {
        // 开启审计功能
        AuditManager.setAuditEnable(true);

        // 设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage -> {
            String className = "";
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            List<StackTraceElement> list = Arrays.stream(stackTrace).filter(s -> s.getClassName().startsWith("cn.demo") && s.getClassName().contains("ServiceImpl") && !s.getClassName().contains("$")).toList();
            // if (CollectionUtils.isNotEmpty(list) && StringUtils.isNotEmpty(list.getFirst().getFileName())){
            if (CollectionUtils.isNotEmpty(list)){
                className = StringUtils.convertClassName(list.getFirst().getClassName()) + "[" + list.getFirst().getMethodName() + "," +list.getFirst().getLineNumber()+"]" ;
            }
            logger.info("{} [{}ms]: {}",className, auditMessage.getElapsedTime(), auditMessage.getFullSql().replace("`", "").replaceAll("[\r\n]", "").replaceAll("\\s+", " "));
        });

        // 使用内置规则自动忽略 null 和 空字符串
        QueryColumnBehavior.setIgnoreFunction(QueryColumnBehavior.IGNORE_EMPTY);
        // 当 IN(...) 条件只有 1 个参数时，是否自动把的内容转换为相等。
        QueryColumnBehavior.setSmartConvertInToEquals(true);

        // 自定义数据方言, 实现数据权限
        DialectFactory.registerDialect(DbType.MARIADB,new MyPermissionDialect());

    }

    @Override
    public void customize(FlexGlobalConfig config) {

    }

    @Override
    public void customize(FlexConfiguration configuration) {
    }
}